<template>
	<view class="u-p-28 bg-white">
		<u-form :model="form" :label-style="labelStyle" :border-bottom="false" label-position="top" ref="uForm">

			<view class="border-title u-m-b-14">
				宠物照片
			</view>
			<upload dir="find_pet" v-model="form.images"></upload>

			<u-divider class="u-m-t-12" half-width="50%">
				<view class="color-80 u-font-10">
					第一张图片会作为封面展示
				</view>
			</u-divider>

			<view class="border-title u-m-b-14 u-m-t-14">
				宠物视频
			</view>
			<upload type="one" placeholder="选择视频" dir="find_pet" filetype="video" v-model="form.video"></upload>


			<u-form-item :border-bottom="false" label="寻主标题">
				<u-input :clearable="false" :custom-style="inputStyle" v-model="form.title" placeholder="请输入" />
			</u-form-item>

			<u-form-item :border-bottom="false" label="分类">
				<radio-button height="44px" v-model="form.category_id" :list="dict.pet_type"></radio-button>
			</u-form-item>

			<u-form-item :border-bottom="false" label="宠物性别">
				<radio-button height="44px" v-model="form.pet_sex" :list="dict.pet_sex"></radio-button>
			</u-form-item>

			<u-form-item :border-bottom="false" label="宠物年龄">
				<view class="u-rela">
					<u-icon @click="showAgeSelect = true" size="40" color="#808080" class="u-abso arrow"
						name="arrow-right"></u-icon>
					<u-input @click="showAgeSelect = true" disabled :custom-style="inputStyle"
						v-model="form.pet_age_name" placeholder="请选择" />
				</view>
				<u-select :default-value="defaultAge" v-model="showAgeSelect" :list="dict.pet_age" label-name="name"
					value-name="id" @confirm="handleSelectAge"></u-select>
			</u-form-item>

			<u-form-item :border-bottom="false" label="拾得时间">
				<view class="u-rela">
					<u-icon @click="showTimeSelect = true" size="40" color="#808080" class="u-abso arrow"
						name="arrow-right"></u-icon>
					<u-input @click="showTimeSelect = true" disabled :custom-style="inputStyle" v-model="form.pick_time"
						placeholder="请选择" />
				</view>
				<u-picker :default-time="form.pick_time" :params="timeParams" v-model="showTimeSelect" mode="time"
					@confirm="handleSelectTime">
				</u-picker>
			</u-form-item>

			<u-form-item :border-bottom="false" label="拾得地点">
				<view class="u-rela">
					<u-icon @click="chooseLocation" size="40" color="#808080" class="u-abso arrow" name="map"></u-icon>
					<u-input @click="chooseLocation" disabled :custom-style="inputStyle" v-model="form.location"
						placeholder="请选择" />
				</view>
			</u-form-item>

			<u-form-item :border-bottom="false" label="拾得详情">
				<u-input :clearable="false" height="220" :custom-style="textareaStyle" type="textarea"
					v-model="form.detail" placeholder="请输入" />
			</u-form-item>

			<view class="border-title">
				联系方式
			</view>
			<view class="sub-form u-m-t-10">
				<u-form :label-style="{color:'#808080'}" label-position="left" label-width="150">
					<u-form-item label="发布者">
						<u-input class="color-3" :clearable="false" input-align="right" v-model="form.publisher"
							placeholder="请输入" />
					</u-form-item>
					<u-form-item label="联系电话">
						<u-input class="color-3" :clearable="false" input-align="right" v-model="form.mobile"
							placeholder="请输入" />
					</u-form-item>
					<u-form-item label="微信号">
						<u-input class="color-3" :clearable="false" input-align="right" v-model="form.wechat"
							placeholder="请输入" />
					</u-form-item>
					<u-form-item :border-bottom="false" label="QQ号">
						<u-input class="color-3" :clearable="false" input-align="right" v-model="form.qq"
							placeholder="请输入" />
					</u-form-item>
				</u-form>
			</view>

			<view class="u-m-t-28">
				<u-checkbox size="34" label-size="34" v-model="form.mobile_is_show" active-color="#FFCF0B">
					<text class="color-3 u-font-30">可以通过手机号进行联系</text>
				</u-checkbox>
			</view>

			<view class="border-title u-m-b-20 u-m-t-26">
				微信二维码(选填)
			</view>
			<upload type="one" dir="find_pet" v-model="form.wechat_qrcode"></upload>

			<view class="submit">
				<view class="btn" @click="submit">发布</view>
			</view>


		</u-form>


	</view>
</template>

<script>
	import upload from '@/pagesPublish/components/upload/upload.vue';
	import radioButton from '@/components/radioButton/radioButton.vue';
	import {
		getUserInfo
	} from '@/api/user';
	import {
		getCommonDataDict,
	} from '@/api/common';

	import {
		findMasterPublish,
		getFindMasterEdit
	} from '@/api/publish';

	export default {
		components: {
			upload,
			radioButton
		},
		data() {

			return {
				defaultAge: [], // 获取详情时设置年龄下拉框的默认值
				form: {
					category_id: 1,
					pet_sex: 1,
					mobile_is_show: true,
					pay_or_free: '',
					images: [],
					video: [],
					wechat_qrcode: [],
					location: '',
					mobile: '',
					publisher: '',
					pet_age_name: '',
					is_personally: false
				},
				dict: {},
				showAgeSelect: false,
				showTimeSelect: false,
				timeParams: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
				},
				labelStyle: {
					borderLeft: '3px solid  #FFCF0B',
					paddingLeft: '5px',
					color: '#333',
					fontSize: '16px',
					height: '16px',
					marginBottom: '10rpx'
				},
				inputStyle: {
					height: '40px',
					background: '#F6F7FB',
					borderRadius: '4px',
					padding: '0 10px',
				},
				textareaStyle: {
					background: '#F6F7FB',
					borderRadius: '4px',
					padding: '12px 10px',
				},
			};
		},
		onLoad(options) {
			this.id = options.id;
		},
		mounted() {
			this.getBaseFilterData();
			this.getUserInfo();

		},
		methods: {
			handleSelectAge(e) {
				this.form.pet_age = e[0].value;
				this.form.pet_age_name = e[0].label;
			},
			handleSelectTime(val) {
				let {
					year,
					month,
					day,
					hour,
					minute
				} = val;
				const cyear = new Date().getFullYear();
				const cmonth = new Date().getMonth() + 1;
				const cday = new Date().getDate();
				const chour = new Date().getHours();
				const cminute = new Date().getMinutes();
				if (year > cyear) {
					year = cyear;
				}
				if (month > cmonth) {
					month = cmonth;
				}
				if (day > cday) {
					day = cday;
				}
				if (hour > chour) {
					hour = chour;
				}
				if (minute > cminute) {
					minute = cminute;
				}
				this.form.pick_time = `${year}-${month}-${day} ${hour}:${minute}`;
			},
			async getEditInfo() {
				const res = await getFindMasterEdit({
					id: this.id
				});
				const data = res.data;
				// 设置图片
				data.images = data.images.map(item => {
					item.url = item.attachment;
					return item;
				})

				// 设置视频
				if (data.video) {
					data.video = [data.video].map(item => {
						item.url = item.attachment;
						return item;
					})
				}
				// 设置微信二维码

				if (data.wechat_qrcode) {
					data.wechat_qrcode = [data.wechat_qrcode].map(item => {
						item.url = item.attachment;
						return item;
					})
				}

				// 设置显示宠物年龄选中
				this.dict.pet_age.map((item, index) => {
					if (item.id === data.pet_age) {
						data.pet_age_name = item.name;
						this.defaultAge = [index];
					}
				})

				// 设置是否展示手机号
				data.mobile_is_show = data.mobile_is_show === 1;
				data.is_personally = data.is_personally === 1;

				this.form = data;


			},
			async getUserInfo() {
				const res = await getUserInfo();
				if (res.data) {
					this.form.mobile = res.data.mobile;
					this.form.publisher = res.data.nickname;
					this.form.qq = res.data.qq;
					this.form.wechat = res.data.wechat;
				}
			},
			async getBaseFilterData() {
				const res = await getCommonDataDict();

				let dict = res.data;

				Object.entries(dict).forEach((item) => {
					const field = item[0];
					const obj = item[1];
					let objArr = [];
					if (field != "pet_age") {
						Object.entries(obj).forEach((sub) => {
							const id = sub[0] * 1;
							const name = sub[1];
							objArr.push({
								id,
								name,
							});
						});
					} else {
						objArr = obj;
					}
					dict[field] = objArr;
				});

				// 给性别添加图标
				dict.pet_sex = dict.pet_sex.map(item => {
					item.image = require(`@/pagesPublish/static/sex_${item.id}.png`);
					item.image_active = require(`@/pagesPublish/static/sex_${item.id}_active.png`);
					return item;
				})

				this.dict = dict;

				// 必须保证字典数据有了在获取详情
				if (this.id) {
					this.getEditInfo();
				}

			},
			chooseLocation() {
				// 编辑时直接将后端拿到的经纬度设置上
				let latitude = "";
				let longitude = "";
				if (this.form.lat) {
					latitude = this.form.lat;
					longitude = this.form.lng;
				}
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.userLocation']) {
							console.log("userLocation位置功能已授权")
							// 如果已授权,直接获取对应参数
							uni.getLocation({
								success: (res) => {
									uni.chooseLocation({
										latitude: latitude || res.latitude,
										longitude: longitude || res.longitude,
										success: (sub) => {
											this.form.location = sub.address;
											this.form.lat = sub.latitude;
											this.form.lng = sub.longitude;
										}
									})
								}
							})
						} else if (!res.authSetting['scope.userLocation']) {
							// 说明此时要获取的位置功能尚未授权,
							// 则设置进入页面时主动弹出，直接授权
							uni.authorize({
								scope: 'scope.userLocation',
								success: (res) => {
									// 授权成功
									console.log(res)
									// 成功后获取对应的位置参数
									uni.getLocation({
										success: (res) => {
											uni.chooseLocation({
												latitude: latitude || res
													.latitude,
												longitude: longitude || res
													.longitude,
												success: (sub) => {
													this.form.location =
														sub.address;
													this.form.lat = sub
														.latitude;
													this.form.lng = sub
														.longitude;
												}
											})
										}
									})
								},
								fail() {
									console.log("位置授权失败")
									uni.showModal({
										content: '检测到您没打开获取信息功能权限，是否去设置打开？',
										confirmText: "确认",
										cancelText: '取消',
										success: (res) => {
											console.log(res)
											if (res.confirm) {
												uni.openSetting({
													success: (res) => {
														console.log(res);
													},
													fail: (err) => {
														console.log(err)
													}
												})
											} else {
												console.log('取消');
											}
										}
									})
								}
							})
						}
					},
					fail() {
						console.log("获取授权信息授权失败")
					}
				})
			},

			async submit() {
				const postData = Object.assign({}, this.form);
				postData.video = postData.video && postData.video[0] || {};
				postData.wechat_qrcode = postData.wechat_qrcode && postData.wechat_qrcode[0] || {};
				postData.mobile_is_show = postData.mobile_is_show ? 1 : 0;
				postData.is_personally = postData.is_personally ? 1 : 2


				await findMasterPublish(postData);

				uni.showModal({
					showCancel: false,
					content: '您的寻主信息已发布成功',
					confirmColor: '#333',
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack();
						}
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.arrow {
		right: 28rpx;
		z-index: 1;
		top: 50%;
		transform: translateY(-50%);
		color: #FFCF0B;
	}

	.submit {
		padding: 32rpx;

		.btn {
			height: 44px;
			line-height: 44px;
			color: #333333;
			font-size: 16px;
			background: #FFCF0B;
			border-radius: 22px;
			text-align: center;
		}
	}

	.sub-form {
		padding: 0 20rpx;
		background: #F6F7FB;
		border-radius: 4px;

		/deep/ .u-form-item {
			padding: 4px 0;
		}
	}

	.border-title {
		&::before {
			height: 70%;
		}
	}
</style>
